import { stringifyCookie } from 'next/dist/compiled/@edge-runtime/cookies'

/**
 * 判断是不是空字符串。null，undefined，""，" "都会返回true
 * @param str
 * @returns
 */
export const isEmpty = (str: string) => {
  if (!str) return true
  if (typeof str == 'number') return false
  if (str.trim() == '') return true
  return false
}

/**
 * 判断是否全是中文
 * @param str
 * @returns
 */
export function isAllChinaLanguage(str: string) {
  let reg = /^[\u4E00-\u9FFF]+$/
  return reg.test(str)
}

/**
 * 是否是手机号码
 * @param phone
 * @returns
 */
export function isPhone(phone: string) {
  return /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(
    phone
  )
}
/**
 * 是否是手机号码(全球范围)
 * @param phone
 * @returns
 */
export function isGlobalPhone(phone: string) {
  return /(\d{1,4})\s?\d{1,4}-?\d{1,9}$/.test(phone)
}
/**
 * 获取随机ID
 */
export const UUID = () => Math.floor(Math.random() * 100000) + ''

export const ToJSON = (obj: any) => JSON.stringify(obj)

/**
 * 时间格式化
 * @param date
 * @param fmt
 * @returns
 */
export const dateFormat = (date: Date, fmt = 'yyyy-MM-dd hh:mm:ss') => {
  var o = {
    'M+': date.getMonth() + 1, //月份
    'd+': date.getDate(), //日
    'h+': date.getHours(), //小时
    'm+': date.getMinutes(), //分
    's+': date.getSeconds(), //秒
    'q+': Math.floor((date.getMonth() + 3) / 3), //季度
    S: date.getMilliseconds(), //毫秒
  }
  if (fmt == null) {
    return date.toDateString()
  }
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + '').substr(4 - RegExp.$1.length)
    )
  //@ts-ignore
  for (var k in o)
    if (new RegExp('(' + k + ')').test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        // @ts-ignore
        RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
      )
  return fmt
}

/**
 * 深拷贝一个对象 注意:函数无法拷贝
 * @param o
 * @returns
 */
export const copyObject = <T>(o: T): T => JSON.parse(JSON.stringify(o))

/**
 * 睡眠函数
 * @param time 睡眠时间（毫秒）
 */
export const sleep = (time = 200): Promise<true> =>
  new Promise((r, _) => setTimeout(() => r(true), time))

/**
 * 密码加密
 * @param str
 * @returns
 */
export function decToHex(str: string) {
  var res = []
  for (var i = 0; i < str.length; i++)
    res[i] = ('00' + str.charCodeAt(i).toString(16)).slice(-4)
  return '\\u' + res.join('\\u')
}
/**
 * 密码解密
 * @param str
 * @returns
 */
export function hexToDec(str: string) {
  str = str.replace(/\\/g, '%')
  return unescape(str)
}
/**
 * 判断是不是网址
 * @param str
 * @returns
 */
export function isURL(str: string) {
  const urlRegex =
    /^(https?:\/\/)([\w.-]+\.[a-zA-Z]{2,})(\/[\w\.-]*)*\/?(:\d{1,5})?$/i
  const ipIP =
    /^(https?:\/\/)?(([01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}([01]?\d{1,2}|2[0-4]\d|25[0-5])(:\d{1,5})?$/
  return ipIP.test(str.trim()) || urlRegex.test(str.trim())
}

/**
 * 创建一个Date对象，主要是解决苹果端无法用 yyyy-MM-dd的格式创建对象
 * @param res
 * @returns
 */
export const newDate = (res: any) => {
  if (typeof res == 'string') {
    return new Date(res.replace(/[-]/g, '/'))
  }
  return new Date(res)
}

/**
 * 如果的一个参数为 null或0或空字符串，就会返回第二个参数
 * @param value
 * @param exists 兜底值
 * @returns 最后的值
 */
export function ifUnExists<T>(value: T, exists: T): T {
  if (typeof value == 'string' && value.trim() == '') {
    return exists
  }
  if (!value) {
    return exists
  }
  return value
}

/**
 * 是否是邮箱
 * @param email
 * @returns
 */
export const isEmail = (email: string) =>
  /^[a-zA-Z0-9._%±]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/.test(email)

/**
 * 解析网址参数
 * @param {string} url
 * @returns
 */
export function parseUrl(url: string) {
  if (url.includes('?')) {
    const querystring = url.split('?')[1]
    const path = url.split('?')[0].split('://')[1]
    const query: any = {}
    querystring.split('&').forEach((item) => {
      const [key, value] = item.split('=')
      query[key] = value
    })
    return {
      path,
      query,
    }
  } else {
    return {
      path: url.split('://')[1],
      query: {},
    }
  }
}
/**
 * 根据年月获取日数
 * @param year
 * @param months
 * @returns
 */
export const getMonthDates = (year: number, months: number) => {
  const arr = [1, 3, 5, 7, 8, 10, 12]
  if (arr.includes(months)) return 31
  if (months != 2) return 30
  if (year % 4 != 0) return 28
  if (year % 100 == 0) return year % 400 == 0 ? 29 : 28
  return 29
}
export const isPhoneEquipment = () => {
  return /Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)
}
export const debounce = (fn: Function, delay: number) => {
  let timer: any = null
  return function (...args: any) {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fn(...args)
    }, delay)
  }
}
export function createResolvablePromise<T = any>() {
  let resolve: (value: T | PromiseLike<T>) => void,
    reject: (reason?: any) => void
  const p = new Promise<T>((res, rej) => {
    resolve = res
    reject = rej
  })
  // @ts-ignore
  return [p, resolve, reject] as const
}
export const isHttpURL = (url: string) => {
  return /^https?:\/\//.test(url)
}
export const stylesList = (styles: any, className: string) => {
  return className
    .split(' ')
    .map((item) => styles[item])
    .join(' ') as string
}
